package xiongguanweb

import com.alibaba.fastjson.JSON
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import xiongguanweb.http.HttpClient
import xiongguanweb.http.OnResponseListener
import xiongguanweb.http.RequestParams
import xiongguanweb.util.AESTool

import javax.servlet.http.HttpSession

class LoginService {

    private static Logger logger = LoggerFactory.getLogger(LoginService.class)
    //用户登录
    def authToken(String name, String pwd, String token, HttpSession session) {
        RequestParams params = new RequestParams()
        params.putBody("loginName", name)
        params.putBody("pwd", AESTool.encryptBase64(pwd, "f15831e69d484a41"))
        params.putBody("deviceId", "web")
        params.putBody("uxKey", getkeyid(session))
        params.putBody("onceToken", token)
        params.putHead("trcode", "1003")

        def resData = [:]
        HttpClient.me().post(session, params, new OnResponseListener() {
            @Override
            void onSuccess(int errorcode, String errormsg, String data) {
                resData.code = errorcode

            }

            @Override
            void onFailure(int errorcode, String errormsg) {
                resData.code = errorcode
                resData.errormsg = errormsg
            }

            @Override
            void onTokenExpired(int errorcode, HttpSession sion) {
                resData.code = 401
            }
        })

        return resData

    }

    /**
     * 获取一次性token
     */
    def String getOnceToken(HttpSession session) {
        RequestParams params = new RequestParams()
        params.putHead("trcode", "1046")

        def resData = ""
        HttpClient.me().post(session, params, new OnResponseListener() {
            @Override
            void onSuccess(int errorcode, String errormsg, String data) {
                def jsonObject = JSON.parseObject(data)
                resData = jsonObject.token
            }

            @Override
            void onFailure(int errorcode, String errormsg) {
                resData = ""
            }

            @Override
            void onTokenExpired(int errorcode, HttpSession sion) {
            }
        })
        return resData
    }

    /**
     * 获取优讯id
     */
    def String getkeyid(HttpSession session) {
        RequestParams params = new RequestParams()
        params.putHead("trcode", "1032")

        def resData = ""
        HttpClient.me().post(session, params, new OnResponseListener() {
            @Override
            void onSuccess(int errorcode, String errormsg, String data) {
                def jsonObject = JSON.parseObject(data)
                resData = jsonObject.id
            }

            @Override
            void onFailure(int errorcode, String errormsg) {
                resData = ""
            }

            @Override
            void onTokenExpired(int errorcode, HttpSession sion) {
            }
        })
        return resData
    }

}
